<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="960" @ok="handleSubmit">
      <BasicForm @register="registerForm" ref="formRef">
          <template #materialSlot="{ model, field }">
            <a-input-search :disabled='isDetail' v-model:value="model[field]" placeholder="请选择产品编号" readonly @search="openMaterial" />
          </template>
      </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="" key="basResourceGroupDefinitionItem" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="basResourceGroupDefinitionItem"
          :loading="basResourceGroupDefinitionItemTable.loading"
          :columns="basResourceGroupDefinitionItemTable.columns"
          :dataSource="basResourceGroupDefinitionItemTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
          >
          <template #associationCodeSlot="props">
            <a-input-search @search="handleAssociationCodeView(props)" placeholder="请选择资源编码" readonly
              v-model:value="props.row.associationCode" :disabled='isDetail'></a-input-search>
          </template>
          <template #useDepartmentNameSlot="props">
            <a-input-search @search="handleDepartNameView(props)" placeholder="请选择班组" readonly
              v-model:value="props.row.useDepartmentName" :disabled='isDetail'></a-input-search>
          </template>
          <template #processNameSlot="props">
            <a-input-search @search="handleProcessNameView(props)" placeholder="请选择工艺" readonly
              v-model:value="props.row.processManagementName" :disabled='isDetail'></a-input-search>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs> 
    <workCenterListSelectModel :multiple="true" @register="workCenterModal" @getSelectResult="handleWorkCenterValue" />
    <DeviceSelectModel :multiple="true" @register="deviceRegister" @getSelectResult="handleDevicehanged" />
    <DepartmentModal @register="departmentRegister" @getSelectResult="handleDepartChanged" />
    <ProcessModal @register="processRegister" @getSelectResult="handleProcesshanged" />
    <!-- 产品 -->
    <materialSelectModel @register="materialRegModal" @getSelectResult="materialhandleSuccess" v-bind="getBindValue" />
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref,reactive} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { JVxeTable } from '/@/components/jeecg/JVxeTable'
    import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
    import {formSchema,basResourceGroupDefinitionItemColumns} from '../BasResourceGroupDefinition.data';
    import {saveOrUpdate,basResourceGroupDefinitionItemList} from '../BasResourceGroupDefinition.api';
    import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
    import { useModal } from '/@/components/Modal';
    import workCenterListSelectModel from '/@/views/components/workCenterListSelectModel.vue';
    import DeviceSelectModel from '/@/views/components/deviceSelectModel.vue';
    import { DepartmentModal } from '/@/views/system/depart/export/select';
    import ProcessModal from '/@/views/components/processManagementSelectModels.vue';
    import materialSelectModel from '/@/views/components/materialSelectModel.vue';
    // Emits声明
    let index: number | null = null;
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const formDisabled = ref(false);
    const refKeys = ref(['basResourceGroupDefinitionItem', ]);
    const activeKey = ref('basResourceGroupDefinitionItem');
    const basResourceGroupDefinitionItem = ref();
    const isDetail = ref()
    const tableRefs = {basResourceGroupDefinitionItem, };
    const basResourceGroupDefinitionItemTable = reactive({
          loading: false,
          dataSource: [],
          columns:basResourceGroupDefinitionItemColumns
    })
    //表单配置
    const [registerForm, {setProps,resetFields, getFieldsValue, setFieldsValue, validate}] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 8}
    });
     //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await reset();
        setModalProps({confirmLoading: false,showCancelBtn:data?.showFooter,showOkBtn:data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        isDetail.value = !!data?.isDetail
        formDisabled.value = !data?.showFooter;
        if (unref(isUpdate)) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
             requestSubTableData(basResourceGroupDefinitionItemList, {id:data?.record?.id}, basResourceGroupDefinitionItemTable)
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //方法配置
    const [handleChangeTabs,handleSubmit,requestSubTableData,formRef] = useJvxeMethod(requestAddOrEdit,classifyIntoFormData,tableRefs,activeKey,refKeys);

    const [deviceRegister, { openModal: openDeviceModal }] = useModal();
    const [workCenterModal, { openModal: openWorkCenterModal }] = useModal();
    const [departmentRegister, { openModal: openDepartModal }] = useModal();
    const [processRegister, { openModal: openProcessModal }] = useModal();
    // 注册产品选择框
    const [materialRegModal, { openModal: openMaterialModal }] = useModal();
    //设置标题
    const title = computed(() => (unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));

    function handleWorkCenterValue(values, _options) {
      const records: any[] = [];
      basResourceGroupDefinitionItemTable.dataSource = [];

      for (let i = 0; i < values.length; i++) {       
        const value =  values[i];    
        const record = {
          associationId: value.item.id ?? "",
          associationCode: value.item.workCenterCode ?? "",
          associationName: value.item.workCenterName ?? "",
          priority: value.item.priority ?? 1,
          processManagementId: value.item.processManagementId ?? "",
          processManagementName: value.item.processManagementName ?? "",
          useDepartmentName: value.item.belongingDepartment ?? "",
          useDepartmentId: value.item.belongingDepartmentId ?? "",
        }
        
        records.push(record)
      }      
      basResourceGroupDefinitionItemTable.dataSource = records;
    }
    function handleDevicehanged(values, _options) {
      basResourceGroupDefinitionItemTable.dataSource = [];
      const records: any[] = []
      for (let i = 0; i < values.length; i++) {
        const value = values[i]
        const record = {
          associationId: value.item.id ?? "",
          associationCode: value.item.code ?? "",
          associationName: value.item.name ?? "",
          priority: value.item.priority ?? 1,
          processManagementId: value.item.processManagementId ?? "",
          processManagementName: value.item.processManagementName ?? "",
          useDepartmentName: value.item.useDepartmentName ?? "",
          useDepartmentId: value.item.useDepartmentId ?? "",
        }
        records.push(record)
      }
      basResourceGroupDefinitionItemTable.dataSource = records;
    }
    function handleDepartChanged(value,_options ) {
        basResourceGroupDefinitionItemTable.dataSource = basResourceGroupDefinitionItem.value!.getTableData();
        basResourceGroupDefinitionItemTable.dataSource[index].useDepartmentId = value[0].value ?? "";
        basResourceGroupDefinitionItemTable.dataSource[index].useDepartmentName = value[0].label ?? "";
    }
    function handleProcesshanged(value, _options) {
      basResourceGroupDefinitionItemTable.dataSource = basResourceGroupDefinitionItem.value!.getTableData();
      basResourceGroupDefinitionItemTable.dataSource[index].processManagementId = value[0].item.id ?? "";
      basResourceGroupDefinitionItemTable.dataSource[index].processManagementName = value[0].item.processName ?? "";
    }
    async function reset(){
      await resetFields();
      activeKey.value = 'basResourceGroupDefinitionItem';
      basResourceGroupDefinitionItemTable.dataSource = [];
    }
    function classifyIntoFormData(allValues) {
         let main = Object.assign({}, allValues.formValue)
         return {
           ...main, // 展开
           basResourceGroupDefinitionItemList: allValues.tablesValue[0].tableData,
         }
       }
    function handleAssociationCodeView(props) {
      index = props.params.$rowIndex;
      const formData = getFieldsValue();
      if (formData.resourceAttribute == 1) {
        openDeviceModal(true, {
          isUpdate: isUpdate.value,
          showFooter: true,
        })
      } else {
        openWorkCenterModal(true, {
          isUpdate: isUpdate.value,
          showFooter: true,
        });
      }

    }
    //打开产品选择
    function openMaterial() {
      openMaterialModal(true, {
        isUpdate: false,
        showFooter: true
      });
    }
    //产品回写
    function materialhandleSuccess(val, values) {
      setFieldsValue({
        materialId: val[0].item.id,
        materialCode: val[0].item.code,
        materialName: val[0].item.name,
      })
    }
    function handleDepartNameView(props) {
        index = props.params.$rowIndex;
        openDepartModal(true, {
          isUpdate: isUpdate.value,
          showFooter: true,
        })
    }
    function handleProcessNameView(props) {
      index = props.params.$rowIndex;
      openProcessModal(true, {
        isUpdate: isUpdate.value,
        showFooter: true,
      });
    }
    //表单提交事件
    async function requestAddOrEdit(values) {
        try {
            setModalProps({confirmLoading: true});
            if(values.specialProductGroup) values.specialProductGroup = 1;
            else values.specialProductGroup = 0;
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
    :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>